import string
import random

from PIL import Image
from django.http import HttpResponse
from utils.resFormatUtil import ResFormat


def verifyParam(*param):  # email, passwrod 不定长
    """
    参数验证装饰器
    1.校验必备参数是否录入
    2.校验参数格式是否正确
    3.发送邮件
    4.响应
    :param param:需要验证的参数
    :return:
    """

    # 装饰器func--->get/post
    def verify(func):
        def isNone(request, *args, **kwargs):  # request.GET/POST.get()
            # 获取参数
            request_param = getattr(request, request.method)  # getattr()获取指定对象的指定属性 request.GET/POST
            # 循环获取要校验的参数
            for i in param:  # i假设--->email
                value = request_param.get(i, None)  # request.GET/POST.get('email')

                if not value:
                    # return HttpResponse("参数错误")
                    return ResFormat(status='PARAM_ERROR').json_response()

            return func(request, *args, **kwargs)  # 回调

        return isNone

    return verify


'''
面向对象 ---》类
属性和方法
属性描述我们类的特征 图像验证码：字符长度，图片宽、高， 字体大小
方法是类的功能， 图像验证码：识别图片字符，干扰设置，
'''


class ImageVerify:
    def __init__(self, length=4, width=140, height=40, size=28):
        """
        初始化
        :param length: 字符长度
        :param width: 图片宽度
        :param height: 图片高度
        :param size: 字体大小
        """
        self.length = length
        self.width = width
        self.height = height
        self.size = size

    def random_str(self):
        """
        随机字符串
        A-Za-z0-9
        :return: 随机字符串
        """
        source = string.ascii_letters + '0123456789'
        return ''.join(random.sample(source, self.length))

    def image_code(self):
        """
        生成图片验证码
        :return:
        """
        # 创建image对象
        image = Image.new('RGB', (self.width, self.height), (255, 255, 255))  # 白色背景图
        return image


if __name__ == '__main__':
    imgVerify = ImageVerify()
    img = imgVerify.image_code()
    with open('test.png', 'wb') as f:
        img.save(f)